<!-- src/views/pages/EmployeeManage.vue -->
<template>
  <div class="employee-manage">
    <!-- 顶栏 -->
    <TopBar />

    <!-- 内容区域 -->
    <div class="content">
      <!-- 菜单 -->
      <MenuLine />

      <!-- 操作栏 -->
      <div class="operation-bar">
        <el-button type="primary" @click="openAddDialog">添加员工</el-button>
      </div>

      <!-- 员工列表 -->
      <el-table :data="employeeList" style="width: 100%" border fit>
        <el-table-column prop="id" label="ID" width="100" />
        <el-table-column prop="name" label="姓名" width="150" show-overflow-tooltip />
        <el-table-column prop="phone" label="电话" width="150" />
        <el-table-column prop="departmentName" label="部门" min-width="200" />
        <el-table-column prop="createTime" label="创建时间" width="250" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="openEditDialog(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteEmployee(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加/编辑弹窗 -->
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="30%"
        @close="resetForm"
      >
        <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
          <el-form-item
            v-for="field in employeeFields"
            :key="field.key"
            :label="field.label"
            :prop="field.key"
          >
            <el-input
              v-if="field.type === 'text'"
              v-model="form[field.key]"
              :placeholder="field.placeholder"
              :maxlength="field.maxLength"
            />
            <el-select
              v-else-if="field.type === 'select'"
              v-model="form[field.key]"
              :placeholder="field.placeholder"
              style="width: 100%"
              :loading="!departmentOptions.length"
              :disabled="field.key === 'departmentId' && isEdit && !isAdmin"
              @click="handleDepartmentSelectClick(field.key)"
              @change="updateDepartmentName"
            >
              <el-option
                v-for="option in departmentOptions"
                :key="option.id"
                :label="option.name"
                :value="option.id"
              />
              <el-option v-if="!departmentOptions.length" disabled label="无可用部门" :value="0" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { useEmployeeStore, employeeFields, type Employee } from '@/stores/employee';
import { useDepartmentStore } from '@/stores/department';
import { useUserStore } from '@/stores/user';
import TopBar from '@/components/TopBar.vue';
import MenuLine from '@/components/MenuLine.vue';

// 员工、部门和用户 store
const employeeStore = useEmployeeStore();
const departmentStore = useDepartmentStore();
const userStore = useUserStore();
const employeeList = ref<Employee[]>([]);

// 部门选项
const departmentOptions = ref<{ id: number; name: string }[]>([]);

// 判断当前用户是否为管理员
const isAdmin = computed(() => userStore.user?.role === 'MANAGER');

// 弹窗控制
const dialogVisible = ref(false);
const dialogTitle = ref('添加员工');
const isEdit = ref(false);
const form = ref<Employee>({
  id: 0,
  name: '',
  phone: '',
  departmentId: undefined,
  departmentName: '',
  createTime: '',
});
const formRef = ref<FormInstance>();

// 表单校验规则
const rules = ref<FormRules>({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 1, max: 20, message: '姓名长度在 1 到 20 字符', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' },
  ],
  departmentId: [
    { required: true, message: '请选择部门', trigger: 'change' },
  ],
});

// 获取员工列表并映射部门名称
const fetchEmployees = async () => {
  try {
    const employees = await employeeStore.fetchEmployees();
    // 映射 departmentName
    employeeList.value = employees.map(employee => ({
      ...employee,
      departmentName: departmentOptions.value.find(dept => dept.id === employee.departmentId)?.name || '未知部门',
    }));
    console.log('员工列表:', employeeList.value);
  } catch (error) {
    ElMessage.error('获取员工列表失败');
    console.error('员工加载失败:', error);
  }
};

// 获取部门选项
const fetchDepartments = async () => {
  try {
    const departments = await departmentStore.fetchDepartments();
    departmentOptions.value = departments.map(dept => ({
      id: dept.id,
      name: dept.name,
    }));
    console.log('部门选项:', departmentOptions.value);
  } catch (error) {
    ElMessage.error('获取部门列表失败');
    console.error('部门加载失败:', error);
  }
};

// 更新表单中的 departmentName
const updateDepartmentName = (departmentId: number) => {
  const dept = departmentOptions.value.find(opt => opt.id === departmentId);
  form.value.departmentName = dept ? dept.name : '';
};

// 处理部门选择框点击
const handleDepartmentSelectClick = (key: string) => {
  if (key === 'departmentId' && isEdit.value && !isAdmin.value) {
    ElMessage.warning('只有管理员可以修改部门');
  }
};

// 打开添加弹窗
const openAddDialog = async () => {
  isEdit.value = false;
  dialogTitle.value = '添加员工';
  await fetchDepartments(); // 确保部门数据加载
  form.value = {
    id: 0,
    name: '',
    phone: '',
    departmentId: departmentOptions.value[0]?.id, // 默认第一个部门，所有用户可选择
    departmentName: departmentOptions.value[0]?.name || '',
    createTime: '',
  };
  dialogVisible.value = true;
};

// 打开编辑弹窗
const openEditDialog = async (row: Employee) => {
  isEdit.value = true;
  dialogTitle.value = '编辑员工';
  await fetchDepartments(); // 确保部门数据加载
  form.value = {
    ...row,
    departmentName: departmentOptions.value.find(dept => dept.id === row.departmentId)?.name || row.departmentName,
  };
  dialogVisible.value = true;
};

// 提交表单（添加或编辑）
const submitForm = async () => {
  if (!formRef.value) return;
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 非管理员编辑时，保留原始 departmentId
        const payload = {
          ...form.value,
          departmentId: isEdit.value && !isAdmin.value ? employeeList.value.find(e => e.id === form.value.id)?.departmentId : form.value.departmentId,
        };
        if (isEdit.value) {
          await employeeStore.updateEmployee(payload);
          ElMessage.success('编辑员工成功');
        } else {
          await employeeStore.createEmployee({
            name: form.value.name,
            phone: form.value.phone,
            departmentId: form.value.departmentId,
          });
          ElMessage.success('添加员工成功');
        }
        dialogVisible.value = false;
        await fetchEmployees();
      } catch (error) {
        ElMessage.error(isEdit.value ? '编辑员工失败' : '添加员工失败');
        console.error('提交失败:', error);
      }
    }
  });
};

// 删除员工
const deleteEmployee = async (id: number) => {
  ElMessageBox.confirm('确定删除该员工吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        await employeeStore.deleteEmployee(id);
        ElMessage.success('删除员工成功');
        await fetchEmployees();
      } catch (error) {
        ElMessage.error('删除员工失败');
        console.error('删除失败:', error);
      }
    })
    .catch(() => {
      ElMessage.info('取消删除');
    });
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.value = {
    id: 0,
    name: '',
    phone: '',
    departmentId: undefined,
    departmentName: '',
    createTime: '',
  };
};

// 初始化加载
onMounted(async () => {
  await fetchDepartments(); // 先加载部门
  await fetchEmployees(); // 再加载员工
  // 确保用户信息已加载（假设登录后已调用 fetchUserInfo）
  if (!userStore.user) {
    console.warn('用户信息未加载');
  }
});
</script>

<style scoped>
.employee-manage {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.content {
  padding-top: 60px; /* 留出顶栏高度 */
  width: 80%; /* 增加宽度以占满空间 */
  margin: 0 auto;
  padding-bottom: 60px; /* 底部留白 */
}

.operation-bar {
  margin: 20px 0;
}

.el-table {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>